package com.L.yygh.user.api;

import com.L.yygh.common.result.Result;
import com.L.yygh.helper.JwtHelper;
import com.L.yygh.model.acl.User;
import com.L.yygh.model.user.UserInfo;
import com.L.yygh.user.Service.UserInfoService;
import com.L.yygh.user.config.HttpClientUtil;
import com.L.yygh.user.config.WxProperties;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信操作的接口
@Api(tags = "微信操作接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoService userInfoService;
    //1.生成微信扫描的二维码
    //返回生成二维码需要的参数
    @ApiOperation("返回生成二维码需要的参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        try{
            Map<String,Object> map = new HashMap<>();
            map.put("appid",wxProperties.getApp_id());
            map.put("scope","snsapi_login");
            String redirect_url = wxProperties.getRedirect_url();
            String encodeURL = URLEncoder.encode(redirect_url, "utf-8");
            map.put("redirect_uri",encodeURL);
            map.put("state",System.currentTimeMillis()+"");
            return Result.ok(map);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return Result.fail();
        }
    }

    //2.微信扫码后回调的方法，得到扫描人的信息
    @GetMapping("callback")
    public String callback(String code,String state){
        //第一步 获取临时票据 code
        System.out.println(code);
        //第二步 拿着code和微信id和秘钥，请求微信固定地址，得到两个值
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(), wxProperties.getApp_id(), wxProperties.getApp_secret(), code);
        try {
            //使用httpclient请求这个地址
            String accessTokenInfo = restTemplate.getForObject(accessTokenUrl,String.class);
//            String accessTokenInfo = HttpClientUtil.get(accessTokenUrl);
            System.out.println("accessTokenInfo:"+accessTokenInfo);

            //从返回的字符串中获取两个值，openid和access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String openid = jsonObject.getString("openid");
            String access_token = jsonObject.getString("access_token");

            //判断数据库是否存在微信的扫描人的信息
            //根据openid进行判断
            UserInfo userInfo = userInfoService.selectWxOpenId(openid);
            if(userInfo == null){
                //第三步 拿着openid和access_token请求微信地址，得到扫描人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl,access_token,openid);
//            String resultInfo = HttpClientUtil.get(userInfoUrl);
                String resultInfo = restTemplate.getForObject(userInfoUrl, String.class);
                System.out.println(resultInfo);
                //解析用户信息
                //用户昵称
                JSONObject jsonObject1 = JSONObject.parseObject(resultInfo);
                String nickname = jsonObject1.getString("nickname");
                //用户头像
                String headimgurl = jsonObject1.getString("headimgurl");

                //将获取的扫描人的信息添加到数据库中
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号为空，返回openid值不是空字符串
            //前端判断：
            //如果openid为空，绑定手机号
            //如果openid不为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //使用jwt生成一个token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:"+ wxProperties.getBaseUrl() +
                    "/weixin/callback?token="+map.get("token")+
                    "&openid="+map.get("openid")+
                    "&name="+URLEncoder.encode((String)map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}
